using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Amazon;
using System.Text.RegularExpressions;

namespace smartBrowser.Task.Annotators
{
    public class AmazonAnnotator : AbstractAnnotator
    {
        private Regex expression = new Regex("^http://www.amazon.com/.*/dp/(.*?)/.*$|^http://www.amazon.com/.*%2Fdp%2F(.*?)%2F.*$|^http://amazon.com/gp/amabot/.*%2FASIN%2F(.*?)%2F.*$");

        public override bool URLMatches(string url)
        {
            if (expression.IsMatch(url))
            {
                return true;
            }

            return false;
        }

        protected override void CreateTooltipThread(HtmlElement link, HtmlDocument document, string linkId)
        {
            if (link.Id == null || link.Id == "")
                link.Id = linkId;


            Item item = LookupProduct(GetASIN(link.GetAttribute("href")));
            if (item == null)
                return;

            HtmlElement divElm = document.CreateElement("div");
            divElm.Id = link.Id + "_tooltip";
            link.SetAttribute("tooltip", divElm.Id);
            divElm.Style = "visibility:hidden; display:block; position:absolute;font-size: x-small; color:#000; text-decoration:none; text-align:left; border: 1px solid #8ac4ff; background: #cee6ff; padding: 0.5em; margin: 0.2em;";
            document.Body.AppendChild(divElm);

            divElm.AppendChild(CreateLeftColumn(document, item));
            divElm.AppendChild(CreateRightColumn(document, item));
            divElm.AppendChild(CreateFooter(document, item));

            string script = @"
                link = document.getElementById('" + link.Id + @"');
		        tooltip = document.getElementById(link.tooltip)
  
		        link.onmouseover = showTooltip;
		        link.onmouseout = tooltipMouseOut;
                link.style.background = 'yellow';

		        tooltip.onmouseover = tooltipMouseOver;
		        tooltip.onmouseout = tooltipMouseOut;
            ";

            HtmlElement scriptElm = document.CreateElement("script");
            scriptElm.SetAttribute("language", "javascript");
            mshtml.HTMLScriptElement scriptElm2 = (mshtml.HTMLScriptElement)scriptElm.DomElement;
            scriptElm2.text = script;

            document.Body.AppendChild(scriptElm);
        }

        private string GetASIN(string url)
        {
            foreach (Group group in expression.Match(url).Groups)
            {
                if (group.Value != "" && !group.Value.StartsWith("http"))
                    return group.Value;
            }

            return "";
        }

        private HtmlElement CreateLeftColumn(HtmlDocument document, Item item)
        {
            HtmlElement divElm = document.CreateElement("div");
            divElm.AppendChild(CreateImageDiv(document, item));
            divElm.Style = "float: left; margin-top: 0; margin-right: 1em; border-right: 1px solid black; padding-top: 0; padding-right: 1em;";
            return divElm;
        }

        private HtmlElement CreateImageDiv(HtmlDocument document, Item item)
        {
            HtmlElement imageDiv = document.CreateElement("div");
            imageDiv.Style = "text-align: center;";

            if (item.LargeImage == null)
                return imageDiv;

            HtmlElement image = document.CreateElement("img");
            image.SetAttribute("src", item.SmallImage.URL);
            image.Style = "border:0;";

            imageDiv.AppendChild(image);

            return imageDiv;
        }

        private HtmlElement CreateRightColumn(HtmlDocument document, Item item)
        {
            HtmlElement divElm = document.CreateElement("div");

            divElm.AppendChild(CreateTitleDiv(document, item));
            divElm.AppendChild(CreateAuthorsDiv(document, item));
            divElm.AppendChild(CreateRatingsDiv(document, item));

            return divElm;
        }

        private HtmlElement CreateTitleDiv(HtmlDocument document, Item item)
        {
            HtmlElement divElm = document.CreateElement("div");
            divElm.InnerText = item.ItemAttributes.Title;
            divElm.Style = "font-weight: bold; margin-bottom: 0.3em; ";
            return divElm;
        }

        private HtmlElement CreateAuthorsDiv(HtmlDocument document, Item item)
        {
            HtmlElement divElm = document.CreateElement("div");
            if (item.ItemAttributes.Author == null)
                return divElm;

            string authors = "by ";
            foreach (string author in item.ItemAttributes.Author)
            {
                authors += author + ", ";
            }
            divElm.InnerHtml = authors.Substring(0, authors.Length - 2);

            return divElm;
        }

        private HtmlElement CreateRatingsDiv(HtmlDocument document, Item item)
        {
            HtmlElement divElm = document.CreateElement("div");
            divElm.Style = "margin-top: 5px;";

            if (item.CustomerReviews == null || !item.CustomerReviews.AverageRatingSpecified)
                return divElm;

            HtmlElement label = document.CreateElement("label");
            label.InnerText = "Average costumer review: ";
            divElm.AppendChild(label);

            decimal rating = item.CustomerReviews.AverageRating;
    		
		    int i;
		    for (i = 1; i <= rating; i++) {
                HtmlElement starImg = document.CreateElement("img");
                starImg.SetAttribute("src", new Uri(System.IO.Path.Combine(Application.StartupPath, "star.png")).AbsoluteUri);
                starImg.SetAttribute("width", "16");
                starImg.SetAttribute("height", "16");
                divElm.AppendChild(starImg);
		    }

		    if (rating - (int) rating >= (decimal) 0.3) {
			    HtmlElement starImg = document.CreateElement("img");
                starImg.SetAttribute("src", new Uri(System.IO.Path.Combine(Application.StartupPath, "star-half.png")).AbsoluteUri);
                starImg.SetAttribute("width", "8");
                starImg.SetAttribute("height", "16");
                divElm.AppendChild(starImg);
			    i++;
		    }

            return divElm;
        }

        private HtmlElement CreateFooter(HtmlDocument document, Item item)
        {
            HtmlElement divElm = document.CreateElement("div");
            divElm.Style = "text-align: right;clear: both;";
            divElm.InnerHtml = "<a href='" + item.DetailPageURL + "'>Visitar</a> | <a href='comprar'>Comprar</a>";
            return divElm;
        }

        private Item LookupProduct(string asin) 
        {
            AWSECommerceService aws = new AWSECommerceService();
            ItemLookup lookup = new ItemLookup();
            lookup.AWSAccessKeyId = "10XXKVYRS9C4CC4BDEG2";
            ItemLookupRequest request = new ItemLookupRequest();
            request.ItemId = new string[] { asin };
            request.ResponseGroup = new string[] { "Medium", "Reviews" };
            ItemLookupRequest[] requests = new ItemLookupRequest[] { request };
            lookup.Request = requests;

            ItemLookupResponse response = aws.ItemLookup(lookup);
            Items info = response.Items[0];
            Item[] items = info.Item;

            if (items == null || items.Length == 0)
                return null;

            return items[0];
        }
    }
}
